<?php
require_once(dirname(__FILE__) ."/File.php");
/**
 * Here is an example
 * <code>
 * $importFields = array("email", "name", "lastname", "birthdate", "gender");
 * $importToTable = "test";
 *
 * if ($_POST['action']=='import')
 * {
 *     // I create the CSVReader object.
 *     $csv = new CSVReader();
 *     $csv->dirPath = DIR_TMP;
 *     $csv->filename = $importFileName;
 *
 *     if ($_FILES['csvFile'])
 *     {
 *         if ($csv->catchPost($_FILES['csvFile'])==UPLOAD_ERR_OK)
 *         {
 *             $csv->savePost();
 *             $csv->separator = $_POST['separator']? $_POST['separator'] : ';';
 *             $csv->enclosure = $_POST['enclosure']? $_POST['enclosure'] : '"';
 *             $csv->firstLineIsHeader = isset($_POST['firstLineIsHeader'])? true : false;
 *             $csv->open();
 *             while($data = $csv->fetchRow())
 *             {
 *                 array_walk($data, 'escapePost');
 *                 $myData = implode("','", $data);
 *                 $sql = "REPLACE INTO ". $importToTable ." (". implode(", ", $importFields) .") VALUES ('". $myData ."')";
 *                 if (!mysql_query($sql)) break;
 *             }
 *             $csv->delete();
 *             unset($csv);
 *         }
 *         else echo "Error al guardar archivo: ". $csv->getErrorMessage();
 *     }
 * }
 * </code>
 * @package utility
 */

class CSVReader extends File
{
    public $separator=";";
    public $enclosure='"';
    public $maxLineLenght=1024;
    public $fields=array();
    public $rowMum=0;
    public $firstLineIsHeader=false;

    public function load($mode="r")
    {
        if (file_exists($this->getPath()))
        {
            $this->size = filesize($this->getPath());
            $this->date_modified = filemtime($this->getPath());
            $this->open($mode);
            return 1;
        }
        return 0;
    }

    public function fetchRow()
    {
        $data = fgetcsv($this->handler, $this->maxLineLenght, $this->separator);
		if ($data)
        {
            $this->rowMum++;
            if ($this->firstLineIsHeader && $this->rowMum==1)
            {
                $this->fields = $data;
                return $this->fetchRow();
            }
        }
        $this->eof();
        return $data;
    }

    public function putRow($values)
    {
        if (is_array($values))
        {
            fputcsv($this->handler, $values, /* delimiter */ $this->separator, $this->enclosure);
        }
    }
}
?>
